/*
 * @Author: your name
 * @Date: 2020-12-30 09:36:44
 * @LastEditTime: 2021-01-23 19:58:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \node-server\routes\users.js
 */
const { checkLoginService,
  registerService, getUserInfoService } = require('../../service/userService.js')
const express = require('express');
const router = express.Router();
const Result = require('../../models/result.js');
const { createToken, parseToekn } = require('../../utils/jwt');
//  req.fields; // 非文件项
// 	req.files; // 文件项

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
//获取用户信息
router.get('/info', async (req, res, next) => {
  const { username } = parseToekn(req)
  const { status, results } = await getUserInfoService(username)
  if (status) {
    new Result(results, '获取用户信息成功').success(res)
  } else {
    new Result({}, "获取用户信息失败").fail(res)
  }
})
//用户登录
router.post('/login', async (req, res, next) => {
  const { username, password } = req.body
  if (username && password) {
    const { status, msg } = await checkLoginService(username, password)
    if (status) {
      const data = {
        token: createToken(username),
        username,
        status,
      }
      new Result(data, msg).success(res)
    } else {
      new Result({}, msg).fail(res)
    }
  }
  else {
    new Result('用户名密码不能为空').fail(res)
  }
})
//用户注册
router.post('/register', async (req, res, next) => {
  const { username, password } = req.body
  if (username && password) {
    const { userId, msg, status } = await registerService(username, password)
    if (userId) {
      const data = {
        userId,
        username
      }
      new Result(data, msg).success(res)
    } else {
      new Result({}, msg).fail(res)
    }
  } else {
    new Result('用户名密码不能为空').fail(res)
  }
})

module.exports = router;
